package com.example.annotation.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.example.annotation.myannotation.MyAnnotation2;


/**
 * @author fz
 * @creation time 2021/5/19
 */
@Component
@Aspect
public class MyAspect {
    //切入点 value值表示凡是用到了MyAnotation这个注解的方法都会被拦截
    @Pointcut("@annotation(com.example.annotation.myannotation.MyAnnotation2)")
    public void pointcut() {
    }

    //前置通知，方法前执行
    @Before(value = "pointcut()")
    public void beforeMethod(JoinPoint joinPoint) throws Exception{
        //获取方法签名
        Signature signature = joinPoint.getSignature();
        Method method = ((MethodSignature) signature).getMethod();
        Method realMethod = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), method.getParameterTypes());
        MyAnnotation2 annotation = realMethod.getAnnotation(MyAnnotation2.class);
        System.out.println("方法前执行");
        System.out.println("获取到的注解属性值为：" + annotation.param());
    }

    //后置通知 方法执行后执行
    @After(value = "pointcut()")
    public void afterMethod() {
        System.out.println("方法后执行");
    }
}
